package com.haoran.dwz.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.haoran.dwz.domain.entities.URLRecycleBin;
import com.haoran.dwz.repository.URLRecycleBinRepository;

@Service
public class URLRecycleBinService {
	@Autowired
	private URLRecycleBinRepository urlRecycleBinRepository;

	/**
	 * 分页查询
	 * 
	 * @param pageable
	 * @return
	 */
	public Page<URLRecycleBin> findByPageable(Pageable pageable) {
		return urlRecycleBinRepository.findAll(pageable);
	}

	/**
	 * 接口调用次数
	 */
	public long count() {
		return urlRecycleBinRepository.count();
	}

	/**
	 * 最后使用时间查询
	 * 
	 * @param stime
	 *            开始时间
	 * @param etime
	 *            截止时间
	 * @return
	 */
	public List<URLRecycleBin> search(Date stime, Date etime) {
		List<URLRecycleBin> resultList = null;
		Specification<URLRecycleBin> querySpecifi = new Specification<URLRecycleBin>() {
			@Override
			public Predicate toPredicate(Root<URLRecycleBin> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<>();
				if (stime != null) {
					// 大于或等于传入时间
					predicates.add(cb.greaterThanOrEqualTo(root.get("lastUsedTime").as(Date.class), stime));
				}
				if (etime != null) {
					// 小于或等于传入时间
					predicates.add(cb.lessThanOrEqualTo(root.get("lastUsedTime").as(Date.class), etime));
				}
				// and到一起的话所有条件就是且关系，or就是或关系
				if (predicates.size() > 0) {
					return cb.and(predicates.toArray(new Predicate[predicates.size()]));
				}
				return cb.conjunction();
			}
		};
		resultList = urlRecycleBinRepository.findAll(querySpecifi);
		return resultList;
	}

	public URLRecycleBin save(URLRecycleBin entity) {
		return urlRecycleBinRepository.save(entity);
	}

	public boolean exists(Long id) {
		return urlRecycleBinRepository.exists(id);
	}

	public URLRecycleBin findOne(Long id) {
		return urlRecycleBinRepository.findOne(id);
	}

	public List<URLRecycleBin> findAll() {
		return urlRecycleBinRepository.findAll();
	}

	public void delete(Long id) {
		urlRecycleBinRepository.delete(id);
	}

	public List<URLRecycleBin> findByUrl(String url) {
		return urlRecycleBinRepository.findByUrl(url);
	}

	public List<URLRecycleBin> findByShortUrl(String shortUrl) {
		return urlRecycleBinRepository.findByShortUrl(shortUrl);
	}

	public void delete(long id, String username) {
		urlRecycleBinRepository.delete(id);
	}
}
